<template>
    <div class="goods-page">
        <headBar class="head flex">
            <div slot="xm-header-center" class="search flex-1 flex flex-align-center">
                <i class="icon icon-search"></i>
                <input type="text" placeholder="搜索商品名、条码、品牌" v-model="keyword">
                <i class="icon clear min" @click="keyword=''"></i>
            </div>
            <div slot="xm-header-right">
                <div class="btn search-btn" @click="search(2)">
                    搜索
                </div>
            </div>
        </headBar>
        <div class="filter-group flex  border-top">
            <div class="filter-item flex-1" @click="salesSortFun" :class="{'active':searchParams.salesSort!=''}">销量<i
                    class="icon icon-tubiao_xia-29 colorD"></i></div>
            <div class="line-v"></div>
            <div class="filter-item priceItem flex-1" @click="priceSortFun" :class="{active: searchParams.priceSort!=''}">价格
                <span>
                    <i class="icon icon-tubiao_shang-28" :class="{active: searchParams.priceSort=='desc'}"></i>
                    <i class="icon icon-tubiao_xia-29" :class="{active: searchParams.priceSort=='asc'}"></i>
                </span>
            </div>
            <div class="line-v"></div>
            <div class="filter-item flex-1" @click="showFilter(3)" :class="{'active':filterIndex==3}">
                <i class="icon-filter color9"></i>筛选
            </div>
        </div>
        <div class="category-group" :class="{'show':isFilter}">
            <div class="category-list">
                <div class="category-item border-bottom panda-item">
                    <div class="tit">熊猫服务</div>
                    <div class="list">
                        <span class="border-1px" :class="{active:searchParams.supplierTypeId==1}" @click="selectPandaService(1)">熊猫自营</span>
                        <span class="border-1px" :class="{active:searchParams.isGoods==1}" @click="selectPandaService(2)">有现货</span>
                        <span class="border-1px" :class="{active:searchParams.isPandaNum==1}" @click="selectPandaService(3)">熊猫币</span>
                        <span class="border-1px" :class="{active:searchParams.openPresale==1}" @click="selectPandaService(4)">可预售</span>
                    </div>
                </div>
                <div class="category-item border-bottom">
                    <div class="tit">热门标签</div>
                    <div class="list">
                        <span class="border-1px" v-for="hot in wareTagsList" @click="selectHot(hot)"
                              :class="{active:hot.active}">{{hot.name}}</span>
                    </div>
                </div>
                <div class="category-item" >
                    <div class="tit">商品品牌</div>
                    <div class="list">
                        <span class="border-1px" v-for="brandItem in brandsList"
                              @click="selectBrand(brandItem)"
                              :class="{active: brandItem.active}">{{brandItem.brandName}}</span>
                    </div>
                </div>
            </div>
            <div class="category-opt  flex">
                <div class="flex-1" @click="resetSelect">清空选项</div>
                <div class="flex-1 btn1" @click="search(1)">确定</div>
            </div>
        </div>

        <section class="search-group border-top"
                 v-infinite-scroll="getWareList"
                 infinite-scroll-distance="5">
            <ul class="cate-list flex">
                <li v-for="item in wareList" @click="openDetail(item.id)">
                    <div class="cell-img">
                        <img :src="item.imageThumb">
                    </div>
                    <div class="cell-info">
                        <h3>{{item.name}}</h3>
                        <div class="price">
                            <span v-if="isLogin"><priceShow :price="item.priceUnit" :unitName="item.unitName"></priceShow></span>
                            <span v-if="!isLogin" @click.stop="toLogin">登录查看</span>
                            <i class="fr">{{item.numberPerBox}}{{item.unitName}}/件</i>
                        </div>
                        <div class="cell-tags">
                            <span class="zy" v-show="item.supplierTypeId==1">自营</span>
                            <span v-show="item.numberInventory>0">现货</span>
                            <span v-show="item.pandaCoinStatus!=-1">熊猫币</span>
                            <span v-show="item.openPresale>0">可预售</span>
                        </div>
                        <p class="company" @click.stop="enterStore(item.supplierId)"><i
                                class="icon icon-dianpu5"></i>{{item.supplierName}}</p>
                    </div>
                </li>
            </ul>
            <div class="flex flex-pack-center loading" v-show="loading">
                <span>正在加载</span>
                <mt-spinner :size="36" color="rgb(100, 100, 100)" type="fading-circle"></mt-spinner>
            </div>
            <section class="last" v-show="isLast && wareList.length>0">
                <div class="tit">
                    老板，已经到底了
                </div>
            </section>
        </section>
        <!--数据为空-->
        <nodata textContent="很抱歉，没有找到您搜索的商品..." v-show="wareList.length==0 && !loading"></nodata>
        <div class="fade" v-show="isFilter" @click="clickFade"></div>
        <xm-loading v-show="loading"></xm-loading>
    </div>
</template>
<script>
    export default {
        props: {},
        data() {
            return {
                isFilter:false,
                filterIndex: 0,
                searchParams: {
                    pageNum: 1,
                    pageSize: 10,
                    siteId:'',//站点id
                    categoryIds: '',
                    labelNames: '', //标签名称
                    brandId: '', //品牌id
                    brandList:[], //品牌id数组
                    labelIds: '', //	标签id(多个以,分隔)
                    priceSort: '', //	按价格排序(desc|asc)
                    salesSort: '',//按销量排序(desc|asc)
                    wareName: '',//商品名(搜索关键字),
                    brandIdList:'',//品牌编号数组串
                    supplierTypeId:'',//供应商类别id 1自营
                    openPresale:'',/*预售字段 1可预售，0不可预售*/
                    isPandaNum:'', //是否有熊猫币筛选 1表示筛选0表示不筛选
                    isGoods:'' //是否有现货筛选条件  1表示筛选0表示不筛选
                },
                keyword:'',
                loading: false,
                isLast: false, //是否为最后一条数据
                isLogin: !!Cookie.get('name'),
                wareList: [], //商品列表
                categoryList: [], //分类列表
                wareTagsList: [], //热门标签列表
                brand: null, //单选品牌
                brandsList:[], //查询的品牌列表
                brands:[],//品牌列表
                categoryIds: null, //分类id


            };
        },
        methods: {
            // 显示筛选
            showFilter(index) {
                this.isFilter=true;
                this.filterIndex=3;
//                index == this.filterIndex ? this.filterIndex = 0 : this.filterIndex = index;
                for(var j=0;j<this.brandsList.length;j++){
                    for(var i=0;i<this.brands.length;i++){
                        if(this.brandsList[j].brandId==this.brands[i].brandId){
                            this.$set(this.brandsList[j],'active', true);
                        }

                    }
                }
            },
            // 打开商品详情
            openDetail(wareId) {
                Cookie.set('scrollTop', document.body.scrollTop);
                Cookie.set('searchParams', JSON.stringify(this.searchParams));
                this.$router.push({name: 'goodsDetail', params: {wareId: wareId}});
            },
            /**
             * 跳转登录页面
             * */
            toLogin(){
                this.$router.push({name: 'login'});
            },
            // 进入商店
            enterStore: function (supplierId) {
                this.$router.push({name: 'store', params: {storeId: supplierId}});
            },
            //点击fade 隐藏
            clickFade() {
                this.isFilter = false;
            },
            /**
             * 按价排序
             * @param <string>  (desc|asc)
             * */
            priceSortFun() {
                if(this.searchParams.priceSort==''){
                    this.searchParams.priceSort='desc';
                }else if(this.searchParams.priceSort=='desc'){
                    this.searchParams.priceSort = 'asc'
                }else {
                    this.searchParams.priceSort='';
                }
                this.searchParams.salesSort = '';
                this.filterIndex = 2;
                this.search();
            },
            /**
             *按销量排序
             * */
            salesSortFun() {
                this.searchParams.salesSort = 'desc';
                this.searchParams.priceSort = '';
                this.filterIndex = 1;
                this.search();
            },
            /**
             * 搜索
             * @param type 1.以分类搜索；2.以关键字搜索
             *
             * */
            search(type) {
                //热门标签
                let labelNames = [];
                let labelIds = [];
                this.searchParams.wareName = '';
                this.searchParams.pageNum = 1;
                this.isLast = false;
                [].forEach.call(this.wareTagsList, (item) => {
                    if (item.active) {
                        labelNames.push(item.name);
                        labelIds.push(item.id);
                    }
                });
                if (type == 1 && (this.searchParams.brandList.length>0 || labelIds.length > 0)) {
                    this.filterIndex=3;
                    //this.keyword = '';
                    /*this.searchParams.brandIdList='';
                    this.searchParams.brandList=[];
                    this.searchParams.brands=[];*/
                } else if (type == 2 && this.keyword != '') {
                    //this.resetSelect();
                    labelNames = [];
                    labelIds = [];
                    this.filterIndex='';
                }
                this.searchParams.wareName = this.keyword;
                this.searchParams.brandIdList=this.searchParams.brandList.join(",");
                this.searchParams.brandId='';
                this.searchParams.labelNames = labelNames.join(',');
                this.searchParams.labelIds = labelIds.join(',');
                this.getWareList();
            },
            /**
             * 获取商品列表
             * */
            getWareList(callback) {
                if (this.loading || this.isLast) {
                    return;
                }
                this.loading = true;
                this.clickFade();
                this.searchParams.siteId = Cookie.get('siteId');
                getWareList(this.searchParams).then(data => {
                    this.loading = false;
                    if (data.returnCode == '000000') {
                        if (this.searchParams.pageNum > 1) {
                            this.wareList = this.wareList.concat(data.result.wareList);
                        } else {
                            this.brandsList = data.result.brandList;
                            [].forEach.call(this.brandsList, item => {
                                this.$set(item, 'active', false)
                            });
                            this.wareList = data.result.wareList;
                        }
                        //最后一页
                        if (data.result.wareList.length < this.searchParams.pageSize) {
                            this.isLast = true;
                        }
                        callback && callback();
                        this.searchParams.pageNum++;
                    }
                })
            },
            /**
             * 加入购物车
             * @param <number> 商品id
             * */
            addPurchase(goodId) {
                this.$router.push({name: 'purchase', params: {goodId: goodId}});
            },
            /**
             * 获取分类和品牌信息
             * */
            getCategoryAndBrand() {
                categoryAndBrand({siteId: Cookie.get('siteId')}).then(data => {
                    if (data.returnCode == '000000') {
                        this.categoryList = data.result.categoryList;
                        [].forEach.call(this.categoryList, item => {
                            this.$set(item, 'active', false)
                        })
                    }
                })
            },
            /**
             * 获取热门标签
             * */
            getHotTags() {
                getHotTags().then(data => {
                    if (data.returnCode == '000000') {
                        this.wareTagsList = data.result.wareTagsList;
                        [].forEach.call(this.wareTagsList, item => {
                            this.$set(item, 'active', false)
                        })
                    }
                })
            },
            /**
             * 根据品牌id刷选
             * @param <object> 品牌
             * @param <number> 分类id
             * */
            selectBrand(brand) {
                this.$set(brand, 'active', !brand.active);
                var brandArray=this.brands;
                var brandFlag=false;
                for(var i=0;i<brandArray.length;i++){
                    if(brandArray[i].brandId==brand.brandId){
                        for(var j=0;j<this.searchParams.brandList.length;j++){
                            if(this.searchParams.brandList[j]==brand.brandId){
                                this.searchParams.brandList.splice(j,1);
                            }
                        }
                        brandFlag=true;
                        this.brands.splice(i,1);
                        return;
                    }
                }
                if(brandFlag==false){
                    this.brands.push(brand);
                    this.searchParams.brandList.push(brand.brandId);
                }

               /* if (this.brand == brand) {
                    for(var i=0;i<this.searchParams.brandIds.length;i++){
                        if(this.searchParams.brandIds[i]==brand.brandId){
                            this.searchParams.brandIds.splice(i,1);
                        }
                    }
                    this.brand = null;
                    console.log(this.searchParams.brandIds);
                    return;
                }
                if (this.brand) {
                    this.$set(this.brand, 'active', !this.brand.active);
                }
                this.brand = brand;
                this.searchParams.brandIds.push(brand.brandId);*/
                //console.log(this.searchParams.brandIds);
            },
            /**
             * 根据热门id筛选
             * @param <number> 标签id
             * */
            selectHot(hot) {
                this.$set(hot, 'active', !hot.active);
            },
            /**
             * 根据熊猫服务筛选
             * @param <number> 标签id
             * */
            selectPandaService(panda_service) {
                /*1熊猫自营 2有现货 3熊猫币 4可预售*/
                if(panda_service==1){
                    this.searchParams.supplierTypeId=this.searchParams.supplierTypeId == 1 ? '' : 1;
                }else if(panda_service==2){
                    this.searchParams.isGoods=this.searchParams.isGoods == 1 ? '' : 1;
                }else if(panda_service==3){
                    this.searchParams.isPandaNum=this.searchParams.isPandaNum == 1 ? '' : 1;
                }else if(panda_service==4){
                    this.searchParams.openPresale=this.searchParams.openPresale == 1 ? '' : 1;
                }
            },
            //重选
            resetSelect() {
                this.searchParams.categoryIds = null;
                [].forEach.call(this.wareTagsList, (item) => {
                    if (item.active) {
                        this.$set(item, 'active', false);
                    }
                });
                for(var  i=0; i<this.brandsList.length;i++){
                    this.$set(this.brandsList[i],'active',false);
                }
                this.brands = [];
                this.searchParams.brandList=[];
                this.searchParams.brandIdList='';
                this.searchParams.labelIds='';
                this.searchParams.labelNames=''
                this.searchParams.supplierTypeId='';
                this.searchParams.isGoods='';
                this.searchParams.isPandaNum='';
                this.searchParams.openPresale='';
                /*if (this.brand) {
                    this.$set(this.brand, 'active', false);
                    this.brand = null;
                }*/
            }
        },
        filters: {},
        created() {
            this.searchParams.brandId = this.$route.params['brandId'] || null;
            this.searchParams.wareName = this.keyword = this.$route.params['wareName'] || '';
            this.searchParams.categoryIds = this.$route.params['cateId'] || null;
            this.searchParams.labelNames = this.$route.params['labelName'] || null;
            this.searchParams.labelIds = this.$route.params['tagId'] || null;
            this.getCategoryAndBrand();
            this.getHotTags();
            if (Cookie.get('searchParams')) {
                this.searchParams = JSON.parse(Cookie.get('searchParams'));
                this.searchParams.pageSize = this.searchParams.pageNum * 10;
                this.searchParams.pageNum = 1;
                this.getWareList(() => {
                    this.searchParams = JSON.parse(Cookie.get('searchParams'));
                    this.keyword = this.searchParams.wareName;
                    setTimeout(function () {
                        document.body.scrollTop = Cookie.get('scrollTop');
                        Cookie.remove('scrollTop');
                        Cookie.remove('searchParams');
                    }, 200)
                });
            } else {
                this.getWareList();
            }

        },
        mounted() {

        },
        watch: {
            keyword: function (newValue, oldValue) {
                this.keyword = newValue.substring(0, 20);
            }
        },
        components: {}
    };
</script>
<style lang="less" scoped>
    @import "./list.less";
    .goods-page .search-group .last .tit {
        padding-left: 0;
        text-align: center;
        background: transparent;
    }

</style>
